/**
 * 
 */
package com.qb.mobile.manager;

import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.qb.mobile.model.Phonebook;
import com.qb.mobile.model.Photo;

/**
 * @author <a href="mailto:dangcongthanhtrung@gmail.com">dangtrung</a>
 * 
 *         ContactsReader.java class
 */
public class ContactsReader {

	private final static String DB_NAME = "phonebook";
	private final static String TABLE_NAME = "phonebook";

	private SQLiteDatabase sampleDB = null;
	private Context context;

	public ContactsReader(Context context) {
		this.context = context;
	}

	/**
	 * @param listOfPhonebook
	 */
	public void getPhonebookFromDatabase(List<Phonebook> listOfPhonebook) {
		listOfPhonebook.clear();
		Cursor c = sampleDB.rawQuery("SELECT * FROM " + TABLE_NAME, null);
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					String id = c.getString(c.getColumnIndex("Id"));
					String name = c.getString(c.getColumnIndex("Name"));
					String phone = c.getString(c.getColumnIndex("Phone"));

					String idPhoto = c.getString(c.getColumnIndex("Id_Photo"));
					byte[] photoBlob = c.getBlob(c.getColumnIndex("Photo"));
					
					Photo photo = null; 
					if(idPhoto !=null && photoBlob !=null)
						photo = new Photo(photoBlob, idPhoto);
					listOfPhonebook.add(new Phonebook(id, name, phone, photo));
				} while (c.moveToNext());
			}
		}
	}

	@SuppressWarnings("static-access")
	public void createOrConnectDatabase() {
		sampleDB = context.openOrCreateDatabase(DB_NAME, context.MODE_PRIVATE,
				null);
		sampleDB.execSQL("CREATE TABLE IF NOT EXISTS "
				+ TABLE_NAME
				+ " (Id  VARCHAR primary key, Name VARCHAR, Phone VARCHAR, Photo Blob, Id_Photo VARCHAR);");
	}

	public void insertPhonebookIntoDatabase(Phonebook phoneBook) {
		ContentValues initialValues = new ContentValues();
		initialValues.put("Id", phoneBook.getId());
		initialValues.put("Name", phoneBook.getName());
		initialValues.put("Phone", phoneBook.getPhones().get(0).getNumber());
		if (phoneBook.getPhoto() != null) {
			initialValues.put("Photo", phoneBook.getPhoto().getPhoto());
			initialValues.put("Id_Photo", phoneBook.getPhoto().getId());
		}
		sampleDB.insert(TABLE_NAME, null, initialValues);
	}

	public void deletePhonebookFromDatabase(String id) {
		sampleDB.delete(TABLE_NAME, "id=" + id, null);
	}
}
